const Mock = require('mockjs');
const { param1Obj, param2Obj, validationUtils } = require('./utils');
const list = require('./modules/list');

const mocks = [...list];

function mockXHR() {
  // mock patch
  // https://github.com/nuysoft/Mock/issues/300
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send;
  Mock.XHR.prototype.send = function () {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false;

      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType;
      }
    }
    this.proxy_send(...arguments);
  };

  function XHR2ExpressReqWrap(respond, validation) {
    return function (options) {
      let result = null;
      const { body, type, url } = options;
      const { isSend, msg, missParams } = validationUtils(
        param1Obj(body),
        validation
      );
      // https://expressjs.com/en/4x/api.html#req
      if (isSend) {
        result = respond({
          method: type,
          body: param1Obj(body),
          query: param2Obj(url)
        });
      } else {
        if (missParams && missParams.length) {
          result = {
            msg,
            missParams
          };
        } else {
          result = {
            msg
          };
        }
      }

      return Mock.mock(result);
    };
  }

  for (const i of mocks) {
    Mock.mock(
      new RegExp(i.url),
      i.type || 'get',
      XHR2ExpressReqWrap(i.response, i.validation)
    );
  }
}

module.exports = {
  mockXHR
};
